<template>
  <div class="app-container t-form-theme-wrap">
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span class="el-icon-document">{{ $t("workflow.start.baseInfo") }}</span>
          <el-button
            style="float: right"
            type="primary"
            @click="goBack"
            size="default"
          >
            {{ $t("workflow.start.back") }}
          </el-button>
        </div>
      </template>
      <!--初始化流程加载表单信息-->
      <biz-project-form
        v-if="formConf.formKey"
        :form-config="formConf"
        @submit="submitForm"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts" nmae="StartFlow">
import { onMounted, provide, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import BizProjectForm from "@/views/formgen/components/BizProjectForm/index.vue";
import { getBusinessFormRequest } from "@/api/workflow/workflow";
import { createFormResultRequest } from "@/api/project/data";
import { closeCurrentTag } from "@/utils/other";
import { i18n } from "@/i18n";
import { MessageUtil } from "@/utils/messageUtil";
import { useUserForm } from "@/views/formgen/components/GenerateForm/hooks/useUserForm";
import { USER_FORM_STATE_KEY } from "@/views/formgen/components/GenerateForm/types/constants";

// Define route and router
const route = useRoute();
const router = useRouter();

interface FormConf {
  formKey: string;
}

interface FormData {
  [key: string]: any;
}

const formConf = ref<FormConf>({
  formKey: ""
});

onMounted(() => {
  getBusinessFormRequest(route.query.deployId as string).then(res => {
    if (res.data) {
      formConf.value.formKey = res.data.formKey;
    }
  });
});

const goBack = () => {
  closeCurrentTag(route);
  router.go(-1);
};

const userFormStore = useUserForm();
const { submitLoading } = userFormStore;
provide(USER_FORM_STATE_KEY, userFormStore);

const submitForm = async (data: FormData) => {
  try {
    if (data) {
      await createFormResultRequest({
        ...data,
        formKey: formConf.value.formKey
      });
      MessageUtil.success(i18n.global.t("formI18n.all.success"));
      goBack();
    }
  } catch (e) {
    console.error(e);
  } finally {
    submitLoading.value = false;
  }
};
</script>
<style lang="scss" scoped>
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.app-container {
  //height: 100%;
}

.box-card {
  width: 100%;
  height: 100%;
  margin-bottom: 20px;
  border: 0px;
  border-radius: 10px;
}

.el-card.is-always-shadow {
  box-shadow: none;
}

.el-tag + .el-tag {
  margin-left: 10px;
}
</style>
